import React, { useState, useEffect } from 'react';
import { Layout, Typography, message } from 'antd';
import FileList from './components/FileList';
import FileToolbar from './components/FileToolbar';
import FileSidebar from './components/FileSidebar';
import { FileService } from '../../../apis/backhub/fileService';
import { FileItem, FileType } from './types';
import styles from './FileMgr.module.css';

const { Content } = Layout;
const { Title } = Typography;

const FileMgrPage: React.FC = () => {
    const [files, setFiles] = useState<FileItem[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [total, setTotal] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [selectedFileType, setSelectedFileType] = useState<FileType | null>(null);
    const [searchKeyword, setSearchKeyword] = useState<string>('');
    const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
    const [currentPath, setCurrentPath] = useState<string>('/');

    useEffect(() => {
        fetchFiles();
    }, [currentPage, pageSize, selectedFileType, searchKeyword, currentPath]);

    const fetchFiles = async () => {
        try {
            setLoading(true);
            const response = await FileService.getFiles({
                page: currentPage,
                pageSize,
                fileType: selectedFileType,
                keyword: searchKeyword,
                path: currentPath,
            });

            setFiles(response.data.items);
            setTotal(response.data.total);
        } catch (error) {
            message.error('获取文件列表失败');
            console.error('获取文件列表失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFileTypeChange = (type: FileType | null) => {
        setSelectedFileType(type);
        setCurrentPage(1);
    };

    const handleSearch = (keyword: string) => {
        setSearchKeyword(keyword);
        setCurrentPage(1);
    };

    const handlePageChange = (page: number, size?: number) => {
        setCurrentPage(page);
        if (size) {
            setPageSize(size);
        }
    };

    const handlePathChange = (path: string) => {
        setCurrentPath(path);
        setCurrentPage(1);
    };

    const handleFileSelect = (fileIds: string[]) => {
        setSelectedFiles(fileIds);
    };

    const handleFileUpload = async (files: File[], path: string) => {
        try {
            setLoading(true);
            await FileService.uploadFiles(files, path);
            message.success('文件上传成功');
            fetchFiles();
        } catch (error) {
            message.error('文件上传失败');
            console.error('文件上传失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFileDelete = async (fileIds: string[]) => {
        try {
            setLoading(true);
            await FileService.deleteFiles(fileIds);
            message.success('文件删除成功');
            setSelectedFiles([]);
            fetchFiles();
        } catch (error) {
            message.error('文件删除失败');
            console.error('文件删除失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFolderCreate = async (folderName: string, path: string) => {
        try {
            setLoading(true);
            await FileService.createFolder(folderName, path);
            message.success('文件夹创建成功');
            fetchFiles();
        } catch (error) {
            message.error('文件夹创建失败');
            console.error('文件夹创建失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleFileDownload = async (fileId: string) => {
        try {
            await FileService.downloadFile(fileId);
        } catch (error) {
            message.error('文件下载失败');
            console.error('文件下载失败:', error);
        }
    };

    return (
        <Layout className={styles.fileManagerLayout}>
            <FileSidebar
                onFileTypeSelect={handleFileTypeChange}
                selectedFileType={selectedFileType}
            />
            <Layout className={styles.fileManagerContent}>
                <Content>
                    <Title level={4} className={styles.pageTitle}>文件管理</Title>
                    <FileToolbar
                        onSearch={handleSearch}
                        onUpload={handleFileUpload}
                        onDelete={() => handleFileDelete(selectedFiles)}
                        onCreateFolder={handleFolderCreate}
                        currentPath={currentPath}
                        selectedFiles={selectedFiles}
                    />
                    <FileList
                        files={files}
                        loading={loading}
                        total={total}
                        currentPage={currentPage}
                        pageSize={pageSize}
                        onPageChange={handlePageChange}
                        onFileSelect={handleFileSelect}
                        selectedFiles={selectedFiles}
                        onPathChange={handlePathChange}
                        currentPath={currentPath}
                        onDownload={handleFileDownload}
                    />
                </Content>
            </Layout>
        </Layout>
    );
};

export default FileMgrPage; 